package com.example.demo.controller;

import com.example.demo.annotation.NoneAuth;
import com.example.demo.constant.MessageConstant;
import com.example.demo.constant.NormalConstant;
import com.example.demo.enums.HttpStatusEnum;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.JsonData;
import com.example.demo.pojo.User;
import com.example.demo.util.TokenHelper;
import com.example.demo.util.TokenModel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TokenHelper tokenHelper;
    @PostMapping("/login")
    @NoneAuth
    public JsonData login(@RequestBody User user){
        User currentUser = userMapper.findByName(user.getUsername());
        if (currentUser!=null && currentUser.getPassword() != null
                && currentUser.getPassword().equals(user.getPassword())) {
            TokenModel model = tokenHelper.create(currentUser.getId());
            return JsonData.buildSuccess(model);
        }
        return JsonData.buildError(HttpStatusEnum.NOT_FOUND.getCode(), MessageConstant.USERNAME_OR_PASSWORD_ERROR);
    }
//
//    @GetMapping("/logout")
//    public boolean logout(HttpSession session){
//        session.removeAttribute("user");
//        return true;
//    }

    @DeleteMapping
    public Object logout(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute(NormalConstant.CURRENT_USER_ID);
        if(userId != null) {
            tokenHelper.delete(userId);
        }
        return JsonData.buildSuccess();
    }



}
